/*
 * tilesetLayer.cpp
 *
 *  Created on: Aug 9, 2013
 *      Author: jason
 */
#include "../../include/Tileset/tilesetLayer.hpp"
#include "../../include/mapLoader.hpp"
#include "../../include/Tileset/tilesetTile.hpp"
#include "../../include/Tileset/tilesetTiles.hpp"
#include "../../include/Tileset/tileset.hpp"
#include <string>
#include <tinyxml.h>

namespace Tmx
{
	Layer::Layer(Map *map, int _depth = 0)
	{
		pMap = map;
		LayerEncodingType = ENCODE_XML;
		LayerCompressionType = COMPRESS_NONE;
		width = 0;
		height = 0;
		depth = _depth;
		opacity = 0;
		visible = 1;
		tile_map = NULL;
	}
	Layer::~Layer()
	{
		if (tile_map) {
			delete[] tile_map;
			tile_map = NULL;
		}
	}
	void Layer::parse(TiXmlNode *layerNode)
	{
		const TiXmlElement *layerElement = layerNode->ToElement();
		name = layerElement->Attribute("name");
		layerElement->Attribute("width",&width);
		layerElement->Attribute("height",&height);
		TiXmlNode *dataNode = layerNode->FirstChild("data");
		TiXmlElement *dataElement = dataNode->ToElement();
		const char *opac = layerElement->Attribute("opacity");
		if (opac) {
			opacity = (float) atof(opac);
		}
		const char *vis = layerElement->Attribute("visible");
		if (vis) {
			if (vis == "0")
				visible = 0;
		}
		const char *encode = dataElement->Attribute("encoding");
		const char *compress = dataElement->Attribute("compression");
		if (encode) {
			if (!strcmp(encode, "base64"))
				LayerEncodingType = ENCODE_BASE64;
			else if (!strcmp(encode, "csv"))
				LayerEncodingType = ENCODE_CSV;
		}
		if (compress) {
			if (!strcmp(compress, "zlib"))
				LayerCompressionType = COMPRESS_ZLIB;
			else if (!strcmp(compress,"gzip"))
				LayerCompressionType = COMPRESS_GZIP;
		}
		tile_map = new Tiles[width*height];
		// Decode
		switch (LayerEncodingType) {
		case ENCODE_XML:
			parseXML(dataNode);
			break;
		case ENCODE_BASE64:
			parseB64();
			break;
		case ENCODE_CSV:
			break;
		}
	} // void Layer::parse(

	void Layer::parseXML(TiXmlNode *dataNode)
	{
		TiXmlNode *tileNode = dataNode->FirstChild("tile");
		int tileCount = 0;
		while (tileNode) {
			TiXmlElement *tileElement = tileNode->ToElement();
			int gid = 0;
			tileElement->Attribute("gid", &gid);
			int tilesetIndex = pMap->FindTilesetIndex(gid);
			if (tilesetIndex != -1) {
				Tileset* tileset = pMap->getTileSet(tilesetIndex);
				tile_map[tileCount] = Tiles(gid, tileset->getFirstGid(), tilesetIndex);
			} else {
				tile_map[tileCount] = Tiles(gid, 0, -1);
			}
			tileNode = dataNode->IterateChildren("tile", tileNode);
			tileCount++;
		}
	}
}



